package com.os.sys.controller;

import com.os.sys.config.MyProps;
import com.os.sys.pojo.SysRole;
import com.os.sys.pojo.SysUser;
import com.os.sys.service.SysRoleService;
import com.os.sys.service.SysUserService;
import com.os.sys.service.bean.MenuTreeNode;
import com.os.util.Tools;
import com.os.util.page.PageRequest;
import com.os.util.page.PageResult;
import entity.Param;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
//import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin
@RequestMapping("/user")
@RefreshScope
@Slf4j
@Validated
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private MyProps myProps;
    //https://www.cnblogs.com/superfj/p/9232482.html
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    HttpServletRequest request;

    @Autowired
    @ApiOperation(value = "查询信息" , notes = "查询所有信息")
    //@ApiImplicitParam(name = "user",value = "用户详情实体类",required = true,dataType = "User")
    @RequestMapping(method = RequestMethod.GET)
    public Result findAll(){
        log.debug("this is findAll in ExpController2222");
        //模拟异常，可以被BaseExceptionHandler捕获
        //int i = 1/0;
        List list =  sysUserService.findAll();
        //System.out.println("this is findAll");
        return new Result(true, StatusCode.OK,"查询成功", sysUserService.findAll());
    }
    @Transactional
    @RequestMapping(value="/doSel", method=RequestMethod.GET)
    public Object doSel(@RequestParam(value="page",required = false) Integer page,
                               @RequestParam(value="pageSize",required = false) Integer pageSize,
                               @RequestParam(value="limit",required = false) Integer limit,
                               @RequestParam(value="user_name",required = false) String user_name){
        if(limit!=null){
            pageSize = limit;
        }
        //业务数据列表
        List<SysUser> dataList = new ArrayList();
        Map map = new HashMap();
        List paramList = new ArrayList();
        if(user_name!=null && user_name.length()>0) {
            paramList.add(new Param("user_name", user_name + "", "String","like"));
        }
        map.put("condstr", Tools.genCondStr("", paramList));
        map.put("authEnable", Boolean.FALSE);
        if(page==null){
            //不分页
            dataList = sysUserService.selectByPage(map);
            Tools.indexOrder(dataList,"user_index");
            return dataList;
        }
        //查询总记录数
        int count = sysUserService.selectCountByParam(map);
        //分页
        String limitCond = " limit "+((page-1)*pageSize )+","+pageSize+" ";
        map.put("limit", limitCond);

        dataList = sysUserService.selectByPage(map);
        PageRequest pageRequest = new PageRequest();
        pageRequest.setPageNum(page);
        pageRequest.setPageSize(limit);
        Map map2 = new HashMap();
        map2.put("condstr", Tools.genCondStr("", paramList));
        PageResult pageResult = sysUserService.selectByPager(pageRequest, map2);
        if(pageResult!=null){
            List<SysUser> userList = (List<SysUser>)pageResult.getContent();
            for (SysUser sysUser: userList) {
                List<SysRole> sysRoleList = sysUserService.getUserRoles(sysUser.getUser_id());
                sysUser.setRole_ids(Tools.getIdsFromList(sysRoleList,"role_id"));
                sysUser.setRole_names(Tools.getStrFromList(sysRoleList,"role_name"));
            }
            Result result = new Result(true, StatusCode.OK,"查询成功2",pageResult.getContent());
            result.setTotalCount(pageResult.getTotalSize());
            result.setTotal(Integer.parseInt(Long.toString(pageResult.getTotalSize())));
            return result;
        }
        Tools.indexOrder(dataList,"user_index",page.toString(), pageSize.toString());
        Result result = new Result(true, StatusCode.OK,"查询成功",dataList);
        result.setTotalCount(new Long(count));
        result.setTotal(count);
        List resultList = new ArrayList();
        resultList.add(result);
        if(limit != null){
            return result;
        }
        return resultList;
    }

    @ApiOperation(value = "按照ID查询信息" , notes = "按照ID查询信息")
    @ApiImplicitParam(name = "user_id",value = "用户ID",required = true,dataType = "String")
    @RequestMapping(value="/selectById/{user_id}", method=RequestMethod.GET)
    public Result selectById(@PathVariable String user_id){
        return new Result(true, StatusCode.OK,"查询成功", sysUserService.selectById(user_id));
    }

    /**
     * 注：如果在insert的路径中，增加了/{user_id}那么代表的是以该user_id为主键创建一条新的记录
     * @param sysUser
     * @return
     */
    @RequestMapping(method = RequestMethod.POST)
    public Result insert(@RequestBody SysUser sysUser){
        sysUserService.insert(sysUser);
        sysUserService.setUserRoles(sysUser.getUser_id(),sysUser.getRole_ids(),true);
        return new Result(true, StatusCode.OK,"添加成功");
    }

    @RequestMapping(value="/{user_id}",method = RequestMethod.PUT)
    public Result update(@PathVariable String user_id ,@RequestBody SysUser sysUser){
        sysUser.setUser_id(user_id);
        sysUserService.update(sysUser);
        sysUserService.setUserRoles(sysUser.getUser_id(),sysUser.getRole_ids(),true);
        return new Result(true, StatusCode.OK,"修改成功!", sysUserService.selectById(user_id+""));
    }
    @RequestMapping(value="/update",method = RequestMethod.POST)
    public Result updateUser( @RequestBody @Valid SysUser sysUser){
        log.info("user="+sysUser);
        sysUserService.update(sysUser);
        sysUserService.setUserRoles(sysUser.getUser_id(),sysUser.getRole_ids(),true);
        return new Result(true, StatusCode.OK,"修改成功", sysUser);
    }

    @RequestMapping(value="/add",method = RequestMethod.POST)
    public Result addUser(@RequestBody SysUser sysUser){
        log.info("user="+sysUser);
        //几个必填项设置默认值，备用
        sysUser.setAuth_enable(false);
        sysUser.setAuth_user_id(0);
        sysUser.setUser_ukey(0);
        sysUser.setRegion_id(0);
        sysUser.setNation_id(0);
        sysUserService.insert(sysUser);
        sysUserService.setUserRoles(sysUser.getUser_id(),sysUser.getRole_ids(),true);
        return new Result(true, StatusCode.OK,"修改成功", sysUser);
    }

    @RequestMapping(value="/{user_id}",method = RequestMethod.DELETE)
    public Result delete(@PathVariable String user_id){
        sysUserService.deleteById(user_id);
        return new Result(true, StatusCode.OK,"删除成功", sysUserService.selectById(user_id+""));
    }

    /**
     * 执行用户登陆操作
     * @param token
     * @return
     */
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public Result userInfo(String token){
        SysUser user =  new SysUser();
        //user.setRoles("admin");
        List<String> roles = new ArrayList();
        //roles.add("editor");
        roles.add("admin");
        user.setRoles(roles);
        return new Result(true, StatusCode.OK, "查询用户信息成功", user);
    }
    /**
     * 执行用户登陆操作
     * @param token
     * @return
     */
    @RequestMapping(value = "/getAuthMenu", method = RequestMethod.GET)
    public Result getAuthMenu(@RequestHeader(value="token") String token){
        log.info("getAuthMenu.token = ", token);
        try {
            log.info("jwtUtil.key=", jwtUtil.getKey());
            if (StringUtils.isNotBlank(token)) {
                Claims claims = jwtUtil.parseJWT(token);
                String user_id = (String) claims.get("jti");
                List<MenuTreeNode> nodeList = sysUserService.queryUserMenu(user_id);
                log.info("getAuthMenu::nodeList = ", nodeList);
                return new Result(true, StatusCode.OK, "查询用户菜单成功", nodeList);
            }
        }catch (Exception e){
            return new Result(false, StatusCode.OK, "查询用户菜单失败", new ArrayList<>());
        }
        //return new Result(true, StatusCode.OK, "查询用户信息成功", nodeList);
        MenuTreeNode node = new MenuTreeNode();
        node.setMenu_id(1);
        node.setMenu_addr("/sys/userlist");
        node.setMenu_name("用户管理");
        node.setMenu_code("100000000000");
        node.setM_p(0);
        node.setImg("user");
        List dataList = new ArrayList();
        dataList.add(node);
        //SysUser user =  new SysUser();
        //user.setRoles("admin");
        return new Result(true, StatusCode.OK, "查询用户信息成功", dataList);
    }

    /**
     * 执行用户登陆操作
     * @param sysUser
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result login(@RequestBody SysUser sysUser){
        log.info("sysUser = "+sysUser);
        if(StringUtils.isNotBlank(sysUser.getUsername())){
            //兼容vue-element-admin登陆
            sysUser.setUser_name(sysUser.getUsername());
            sysUser.setUser_pwd(sysUser.getPassword());
        }
        sysUser = sysUserService.login(sysUser.getUser_name(), sysUser.getUser_pwd());
        if(sysUser==null){
            return new Result(false, StatusCode.LOGINERROR, "登录失败");
        }
        //查询数据库，获取该用户具备的角色
        String role_ids = sysUser.getRole_ids();
        role_ids = "1";
        //Map map = new HashMap();
        List roleList = sysRoleService.selectByRole_Ids(role_ids);
        //Tools.getIdsFromList(roleList, "role_id");

        String token = jwtUtil.createJWT(sysUser.getUser_id(), sysUser.getUser_name(), "user");
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("roles", role_ids);
        String key = "role_ids_"+role_ids;
        if(redisTemplate.opsForValue().get(key)==null){
            //查询某些角色对应的菜单 todo
            List menuList = new ArrayList();
            log.debug("向redis保存数据...");
            //存入redis
            redisTemplate.opsForValue().set(key,menuList);
        }else{
            //redisTemplate.opsForValue().set("k","v");
            log.debug("redis中已有数据...");
        }
        sysUserService.genUserInfo(sysUser);
        //redisTemplate.opsForValue().set();
        return new Result(true, StatusCode.OK, "登录成功", map);
    }

    /**
     * 执行用户登陆操作
     * @param token
     * @return
     */
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public Result logout(@RequestHeader("token") String token){
        SysUser user =  new SysUser();
        //user.setRoles("admin");
        //需作废该token,存入REDIS缓存
        return new Result(true, StatusCode.OK, "查询用户信息成功", user);
    }

    @RequestMapping(value = "/index",method = RequestMethod.GET)
    public String index(){
        return "index";
    }


}
